var app = getApp()
Page({
  data: {
    nocheckIconUrl: '../../images/icon_nocheck.png',
    checkIconUrl: '../../images/icon_checked_red.png',
    chooseAddressVal: ''
  },
  onLoad: function (e) {
    if(e && e.type){
      this.setData({
        chooseDefaultType: e.type
      })
    }
    console.log(this.data.chooseDefaultType);
  },
  onShow: function () {
    var that = this;
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_address_list'
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          var addressList = res.data.data;
          var defaultId = '';
          var curAddressData = '';
          for (var i = 0; i < addressList.length; i++) {
            if (addressList[i].isdefault == '1') {
              defaultId = addressList[i].id;
              curAddressData = addressList[i];
              that.setData({
                curAddressData: curAddressData
              })
            }
          }
          that.setData({
            addressList: addressList,
            chooseAddressVal: defaultId
          })
          var chooseType = that.data.chooseDefaultType;
          // if (chooseType) {
          //   wx.getStorage({
          //     key: 'submitOrder',
          //     success: function (res) {
          //       console.log(res.data)
          //       var orderInfo = res.data;
          //       orderInfo.address = curAddressData;
          //       wx.setStorage({
          //         key: "submitOrder",
          //         data: orderInfo,
          //         success: function () {
          //           console.log('存储编辑地址成功');
          //         }
          //       })
          //     }
          //   })
          // }
        } else {
          that.setData({
            addressList: [],
            chooseAddressVal: ''
          })
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
    if(that.data.chooseDefaultType ) {
      wx.getStorage({
        key: 'submitOrder',
        success: function (res) {
          var orderInfo = res.data;
          console.log('orderInfo',orderInfo)
          orderInfo.replace = true
          wx.setStorage({
            key: "submitOrder",
            data: orderInfo
          })
        }
      })
    }
  },
  chooseAddress: function (e) {
    var that = this;
    var curAddressId = e.currentTarget.dataset.id;
    var chooseAddressVal = that.data.chooseAddressVal;
    if (curAddressId == chooseAddressVal) {
      console.log(that.data.chooseDefaultType);
      console.log('333333333')
      if (that.data.chooseDefaultType =='waitorder'){
        console.log('22222222222',)
        wx.getStorage({
          key: 'submitOrder',
          success: function (res) {
            console.log(res.data)
            var orderInfo = res.data;
            console.log(orderInfo)
            if(orderInfo.common) {
              orderInfo.common.address = that.data.curAddressData;
            }else {
              orderInfo.address = that.data.curAddressData;
            }
            
            that.changepostmoney(orderInfo);
          }
        })
      }
      return;
    }
    //发起请求，获取列表列表
    wx.showLoading({
      title: '设置中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_address_default',
        id: curAddressId
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data);
          that.setData({
            chooseAddressVal: curAddressId
          })
          var chooseType = that.data.chooseDefaultType;
          if (chooseType) {
            console.log('111111111111',chooseType)
            var curAddressData = res.data.data.addressData;
            wx.getStorage({
              key: 'submitOrder',
              success: function (res) {
                console.log(res.data)
                var orderInfo = res.data;
                console.log(orderInfo)
                if(orderInfo.common) {
                  orderInfo.common.address = curAddressData;
                }else {
                  orderInfo.address = curAddressData;
                }
                
                that.changepostmoney(orderInfo);
              }
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.em,
            showCancel: false
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  editAddress: function (e) {
    var that = this;
    var editId = e.currentTarget.dataset.id;
    var addressList = that.data.addressList;
    var curEditaddress = {};
    for (var i = 0; i < addressList.length; i++) {
      if (addressList[i].id == editId) {
        curEditaddress = addressList[i]
      }
    }
    console.log(curEditaddress);
    wx.setStorage({
      key: "curEditaddress",
      data: curEditaddress,
      success: function () {
        wx.navigateTo({
          url: '/subpages/editAddress/editAddress?type=edit'
        })
      }
    })
  },
  addAddress: function () {
    wx.navigateTo({
      url: '/subpages/addAddress/addAddress?type=add'
    })
  },
  getweChatAddress: function () {
    var that = this;
    console.log("AAA");
    wx.getSetting({
      success(res) {
        console.log(res);
        if (!res['scope.address']) {
          wx.authorize({
            scope: 'scope.address',
            success() {
              wx.chooseAddress({
                success: function (res) {
                  console.log(res);
                  // 保存获取到的地址到数据库
                  that.saveAddress(res);
                }
              })
            },
            fail(res){
              that.setData({
                showOpensetting: true
              })
            }
          })
        }else{
          
        }
      },
      fail(res) {
        console.log(res);
      }
    })
  },
  hideopenTip:function(){
    var that = this;
    that.setData({
      showOpensetting: false
    })
  },
  openSetting:function(){
    var that = this;
    wx.openSetting({
      success(res) {
        console.log(res.authSetting)
        if (res.authSetting['scope.address']){
          wx.chooseAddress({
            success: function (res) {
              console.log(res);
              // 保存获取到的地址到数据库
              that.saveAddress(res);
            }
          })
        }
      },
      fail(res){
        console.log(res)
      },
      complete(){
        that.hideopenTip();
      }
    })
  },
  saveAddress: function (res) {
    var that = this;
    var data = {};
    data.map = 'applet_address_add';
    data.name = res.userName;
    data.mobile = res.telNumber;
    data.address = res.detailInfo;
    data.pro = res.provinceName;
    data.city = res.cityName;
    data.area = res.countyName;
    data.code = res.postalCode;
    console.log(data);
    //发起请求，获取列表列表
    wx.showLoading({
      title: '正在提交',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          console.log(that.data.operaType);
          wx.showToast({
            title: res.data.data.msg,
            icon: 'success',
            duration: 2000,
            success: function () {
              if (that.data.operaType == 'orderadd') {
                var curAddressData = res.data.data.address;
                wx.getStorage({
                  key: 'submitOrder',
                  success: function (res) {
                    console.log(res.data)
                    var orderInfo = res.data;
                    orderInfo.address = curAddressData;
                    orderInfo.replace = true
                    wx.setStorage({
                      key: "submitOrder",
                      data: orderInfo,
                      success: function () {
                        wx.navigateBack({
                          delta: 1
                        })
                      }
                    })
                  }
                })
              }
              that.onShow();
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.em,
            showCancel: false
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  changepostmoney:function(data){
    var that = this;
    console.log("---------修改地址后",data)
    // var goods=[];

    if(data.common) {
      var prov=data.common.address.province;
      var city = data.common.address.city;
      var district = data.common.address.area;
      var detail = data.common.address.detail;
      var province = data.common.address.province;
      var district = data.common.address.area;
      var town = data.common.address.town;
      var trades = data.trade_list
    }else {
      var prov=data.address.province;
      var city = data.address.city;
      var district = data.address.area;
      var detail = data.address.detail;
      var province_id = data.address.province_id;
      var city_id = data.address.city_id;
      var district_id = data.address.district_id;
    }
    
    if(data.trade_list) {
      var trades = data.trade_list
        .map(v=>{
          return {tid:v.tid,goods:v.goodsData
          .map(k=>{
            return {gid:k.id,num:k.num,gfid:k.gfid}
          })
        }
      });

      console.log(trades);
      
    }else {
      var trades =[{
          tid:data.tid,
          goods:[{
            gid:data.goodsData[0].gid,
            num:data.goodsData[0].num,
            gfid:data.goodsData[0].gfid
          }]
        }]
    }
    trades = JSON.stringify(trades);
      // [{tid :113323,goods}]
      // data.trade_list
      // for(var i=0;i<data.goodsData.length;i++){
      //   goods[i] = {
      //     gid: data.goodsData[i].id,
      //     num: data.goodsData[i].num,
      //     gfid: data.goodsData[i].gfid
      //   }
      // }
  
    console.log(prov);

    console.log(city);
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_get_post_fee_v2',
        prov: prov,
        province:province,
        city:city,
        district:district,
        town:town,
        detail:detail,
        trade:trades
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.ec == 200) {
          console.log("------选择后的运费信息",res.data.data)
          console.log("----总价计算参数")
          if(data.common) {
            var total = parseFloat(data.common.total - data.common.totalPostFee + res.data.data.total_post_fee);
            data.common.total =  Number(total.toFixed(2));  //更新总价
            data.common.totalPostFee = (res.data.data.total_post_fee).toFixed(2); //更新总运费
          }else {
            var total = parseFloat(data.goodsData[0].price)+ parseFloat(res.data.data.total_post_fee);
            console.log('total',res.data.data.total_post_fee,data.goodsData[0].price)
            data.total =  Number(total.toFixed(2));  //更新总价
            data.postTotal = (res.data.data.total_post_fee).toFixed(2); //更新总运费
          }
          if(data.trade_list) {
            data.trade_list.forEach(v=>{  //更新每个订单的运费
              let fee = res.data.data.trade_fee.filter(t=>t.tid==v.tid);
              v.postTotal = fee[0].post_fee;
            })
          }
          console.log('地址更换',data)
          wx.setStorage({
            key: "submitOrder",
            data: data,
            success: function () {
              wx.navigateBack({
                delta: 1
              })
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.em,
            showCancel: false
          });
        }
      },
      complete: function () {
      }
    });
  }
})